package com.hjy.core.transport;

import com.hjy.common.entity.RpcRequest;
import com.hjy.common.entity.RpcResponse;
import com.hjy.core.transport.netty.client.NettyClient;
import com.hjy.core.transport.socket.client.SocketClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

/**
 * Rpc 客户端动态代理, 用于获取接口的动态代理类(Socket 和 Netty 两种类型)
 */
public class RpcClientProxy implements InvocationHandler {
    private final RpcClient client;

    public RpcClientProxy(RpcClient client) {
        this.client = client;
    }

    /**
     * 在这里，我们显然就需要生成一个RpcRequest对象，发送出去，然后返回从服务端接收到的结果即可：
     *
     * @param clazz
     * @param <T>
     * @return
     */
    public <T> T getProxy(Class<T> clazz) {
        return (T) Proxy.newProxyInstance(clazz.getClassLoader(), new Class<?>[]{clazz}, this);
    }


    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        RpcRequest rpcRequest = RpcRequest.builder()
                .interfaceName(method.getDeclaringClass().getName())
                .methodName(method.getName())
                .parameters(args)
                .paramTypes(method.getParameterTypes())
                .build();
        RpcResponse rpcResponse = null;
        if (client instanceof NettyClient) {
            try {
                rpcResponse = (RpcResponse) client.sendRequest(rpcRequest);
            } catch (Exception e) {
                System.out.println("Netty方法调用请求发送失败" + e);
                return null;
            }
        }
        if (client instanceof SocketClient) {
            try {
                rpcResponse = (RpcResponse) client.sendRequest(rpcRequest);
            } catch (Exception e) {
                System.out.println("Socket方法调用请求发送失败" + e);
                return null;
            }
        }
        return rpcResponse.getData();
    }
}
